//
//  ShoppingViewController.m
//  HWZB
//
//  Created by 许成雄 on 2017/4/13.
//  Copyright © 2017年 wonders. All rights reserved.
//

#import "ShoppingViewController.h"
#import "CommodityCollectionViewCell.h"
#import "HACursor.h"
#import "CommodityInfo.h"
#import "CommodityDetailViewController.h"
#import "HWZBAPIRequest.h"

//下拉刷新，上拉加载
#import <MJRefresh/MJRefresh.h>
#import "MyRefreshHeader.h"

@interface ShoppingViewController () <UICollectionViewDelegate, UICollectionViewDataSource, HACursorDelegate>

@property (strong, nonatomic) HACursor *mHACursor;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *typeArray;
@property (strong, nonatomic) NSMutableArray *cardArray;
@property (assign, nonatomic) NSInteger selectIndex;
@property (strong, nonatomic) NSString *typeId;           //0 -- 油卡, 1--充值卡, 2 -- 手机


@end

@implementation ShoppingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = I_COLOR_BACKGROUND;
    self.navigationItem.title = @"铧为至宝商城";
    
    self.selectIndex = 0;
    self.typeId = nil;
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDelegate && UICollectionViewDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = self.cardArray != nil ? [self.cardArray count] : 0;
    return count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (SCREEN_WIDTH - 3 * TRANS_VALUE(5.0f)) / 2;
    return CGSizeMake(width, TRANS_VALUE(166.0f));
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CommodityInfo *commodityInfo = nil;
    if(indexPath.row < [self.cardArray count]) {
        commodityInfo = [self.cardArray objectAtIndex:indexPath.row];
    }
    
    CommodityCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CommodityCollectionViewCell" forIndexPath:indexPath];
    if(!cell) {
        CGFloat width = (SCREEN_WIDTH - 3 * TRANS_VALUE(5.0f)) / 2;
        cell = [[CommodityCollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, width, TRANS_VALUE(166.0f))];
    }
    cell.backgroundColor = [UIColor clearColor];
    
    if(commodityInfo) {
        cell.commodityInfo = commodityInfo;
    } else {
        cell.hidden = YES;
    }
    
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    UIEdgeInsets inset = UIEdgeInsetsMake(0, TRANS_VALUE(5.0f), TRANS_VALUE(5.0f), TRANS_VALUE(5.0f));
    return inset;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return TRANS_VALUE(5.0f);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return TRANS_VALUE(5.0f);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //TODO--跳转到商品详情页面
    CommodityDetailViewController *commodityDetailViewController = [[CommodityDetailViewController alloc] init];
    CommodityInfo *commodityInfo = [self.cardArray objectAtIndex:indexPath.row];
    commodityDetailViewController.commodityId = commodityInfo.commodityId;
    commodityDetailViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:commodityDetailViewController animated:YES];
    
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


#pragma mark - HACursorDelegate
- (void)cursor:(HACursor *)cursor selectedAtIndex:(NSInteger)index {
    if(index == self.selectIndex) {
        return;
    }
    if(index < [self.typeArray count]) {
        //TODO -- 刷新tableview
        NSLog(@"刷新第%ld个tableview....", (long)index);
        self.selectIndex = index;
        if(self.selectIndex == 0) {
            self.typeId = nil;
        } else if(self.selectIndex == 1) {
            self.typeId = @"1";
        } else if(self.selectIndex == 2) {
            self.typeId = @"2";
        } else {
            self.typeId = @"3";
        }
        //刷新tableview
        [self loadTableData];
    }
}

#pragma mark - Private Method
- (void)createUI {
    
    self.mHACursor = [[HACursor alloc] init];
    self.mHACursor.frame = CGRectMake(0, 0, SCREEN_WIDTH, TRANS_VALUE(34));
    self.mHACursor.titles = self.typeArray;
    self.mHACursor.pageViews = [self createPageViews];
    //设置根滚动视图的高度
    if(SCREEN_WIDTH == 320 && SCREEN_HEIGHT <= 568) {
        self.mHACursor.rootScrollViewHeight = SCREEN_HEIGHT - 20.0f - TRANS_VALUE(80.0f);
    } else {
        self.mHACursor.rootScrollViewHeight = SCREEN_HEIGHT - 10.0f - TRANS_VALUE(80.0f);
    }
    
    self.mHACursor.backgroundColor = I_COLOR_WHITE;
    //默认值是白色
    self.mHACursor.titleNormalColor = I_COLOR_33BLACK;
    //默认值是白色
    self.mHACursor.titleSelectedColor = I_COLOR_RED;
    //是否显示排序按钮
    self.mHACursor.showSortbutton = NO;
    //默认的最小值是5，小于默认值的话按默认值设置
    self.mHACursor.minFontSize = TRANS_VALUE(14.0f);
    //默认的最大值是25，小于默认值的话按默认值设置，大于默认值按设置的值处理
    //cursor.maxFontSize = 30;
    //cursor.isGraduallyChangFont = NO;
    //在isGraduallyChangFont为NO的时候，isGraduallyChangColor不会有效果
    //cursor.isGraduallyChangColor = NO;
    [self.view addSubview:self.mHACursor];
    
    self.mHACursor.delegate = self;
    
}

- (NSMutableArray *)createPageViews {
    NSMutableArray *pageViews = [NSMutableArray array];
    for (NSInteger i = 0; i < self.typeArray.count; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - TRANS_VALUE(34.0f) - 49.0f)];
        view.backgroundColor = I_COLOR_WHITE;
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(5.0f), SCREEN_WIDTH, SCREEN_HEIGHT - 64 - TRANS_VALUE(34.0f) - 49.0f - TRANS_VALUE(5.0f)) collectionViewLayout:layout];
        [view addSubview:collectionView];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = I_COLOR_WHITE;
        collectionView.showsVerticalScrollIndicator = NO;
        [collectionView registerClass:[CommodityCollectionViewCell class] forCellWithReuseIdentifier:@"CommodityCollectionViewCell"];
        //设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
        MyRefreshHeader *header = [MyRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadTableData)];
        collectionView.mj_header = header;
        view.tag = i + 10000;
        [pageViews addObject:view];
    }
    return pageViews;
}


- (void)loadData {
    [self loadTypeInfo];
}

- (void)loadTypeInfo {
    if(!self.typeArray) {
        self.typeArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    [self.typeArray removeAllObjects];
    [self.typeArray addObjectsFromArray:@[@"全部", @"油卡", @"话费卡", @"手机"]];
    [self createUI];
    [self loadTableData];
}

- (void)loadTableData {
    if(!self.cardArray) {
        self.cardArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    [self.cardArray removeAllObjects];
    //加载商品列表
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    [params setObject:@"1" forKey:@"page"];
    [params setObject:@"1" forKey:@"isIndex"];
    if(self.typeId) {
        [params setObject:self.typeId forKey:@"productTypeId"];
    }
    [[HWZBAPIRequest sharedInstance] getCommoditiesWithParams:params success:^(NSArray *commodityArray) {
        if(commodityArray != nil) {
            [self.cardArray addObjectsFromArray:commodityArray];
//            [self sortCommodityList:commodityArray];
        }
        UIView *view = (UIView *)[self.view viewWithTag:(self.selectIndex + 10000)];
        UICollectionView *collectionView = (UICollectionView *)[view.subviews objectAtIndex:0];
        [collectionView.mj_header endRefreshing];
        [collectionView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@", [error localizedDescription]);
        UIView *view = (UIView *)[self.view viewWithTag:(self.selectIndex + 10000)];
        UICollectionView *collectionView = (UICollectionView *)[view.subviews objectAtIndex:0];
        [collectionView.mj_header endRefreshing];
        [collectionView reloadData];
    }];
}

- (void)sortCommodityList:(NSArray *)commodityList {
    if(self.selectIndex == 0) {
         [self.cardArray addObjectsFromArray:commodityList];
    } else {
        NSString *type = nil;
        if(self.selectIndex == 1 ) {
            type = @"1";
        } else if(self.selectIndex == 2) {
            type = @"2";
        } else if(self.selectIndex == 3) {
            type = @"3";
        }
        for(int i = 0, n = (int)commodityList.count; i < n; i++) {
            CommodityInfo *commodityInfo = (CommodityInfo *)[commodityList objectAtIndex:i];
            if([commodityInfo.typeId isEqualToString:type]) {
                [self.cardArray addObject:commodityInfo];
            }
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
